package com.ruoyi.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.fastjson2.JSON;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.alibaba.fastjson2.JSONReader.Feature.NullOnError;
import static com.alibaba.fastjson2.JSONWriter.Feature.WriteMapNullValue;

public class Ai {
    public static String callWithMessage(String prompt) throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();
        long start = System.currentTimeMillis();
        Constants.apiKey = "sk-c5133e0081ba4456b401327d4c80b4e9";
        GenerationParam params = GenerationParam.builder().model("qwen-max")
                .prompt(prompt)
                .seed(1234)
                .topP(0.8)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .enableSearch(false)
                .maxTokens(1000)
                .temperature((float) 0.85)
                .repetitionPenalty((float) 1.0)
                .build();

        GenerationResult result = gen.call(params);
        //System.out.println(result.getOutput().getText());
        Message message = result.getOutput().getChoices().get(0).getMessage();
        System.out.println(prompt);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        String content = message.getContent();

        System.out.println(content);
        if (content.startsWith("```json") && content.endsWith("```")) {
            content = content.substring(7, content.length() - 3);
        }
        return content;
    }

    /**
     * openai
     */
    public static String openai(String message) throws Exception {
        System.out.println(message);
        OpenAiChatOptions openAiChatOptions = OpenAiChatOptions.builder()
                .withResponseFormat(new OpenAiApi.ChatCompletionRequest.ResponseFormat("json_object"))
                .withModel("gpt-3.5-turbo").withTemperature(0.5f).withTopP(1f).build();
        Prompt prompt = new Prompt(message, openAiChatOptions);

        ChatClient chatClient = SpringUtil.getBean(ChatClient.class);
        String result = chatClient.call(prompt).getResult().getOutput().getContent();
        return result;
    }

    /**
     * openai
     */
    public static String openaiHttp(String message) throws Exception {
        long start = System.currentTimeMillis();
        Map requestParam = new HashMap();
        requestParam.put("model", "grok-3");
        List<Map> messages = new ArrayList();
        messages.add(Map.of("role", "user", "content", message));
        requestParam.put("messages", messages);
        HttpRequest httpPost = HttpUtil.createPost("https://sg.uiuiapi.com/v1/chat/completions");
        httpPost.addHeaders(Map.of("Authorization", "Bearer sk-pgUdZvSHuP83FXL7ksfjxQ4Ya249lGFFmSdqkiOblizQED0G"));
        httpPost.body(JSON.toJSONString(requestParam));
        String result = httpPost.execute().body();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(result);
        String response = JSON.parseObject(result).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
        System.out.println(response);
        return response;
    }


    /**
     * openai
     */
    public static String mistral(String message) throws Exception {
        long start = System.currentTimeMillis();
        Map requestParam = new HashMap();
        requestParam.put("model", "codestral-latest");
        List<Map> messages = new ArrayList();
        messages.add(Map.of("role", "user", "content", message));
        requestParam.put("messages", messages);
        HttpRequest httpPost = HttpUtil.createPost("https://api.mistral.ai/v1/chat/completions");
        httpPost.addHeaders(Map.of("Authorization", "Bearer a0xg2oIhE2NC4NlW6CKMQj0g7LGmlwlk"));
        httpPost.body(JSON.toJSONString(requestParam));
        String result = httpPost.execute().body();
        long end = System.currentTimeMillis();
        System.out.println(message);
        System.out.println(end - start);
        System.out.println(result);
        String response = JSON.parseObject(result).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
        System.out.println(response);
        return response;
    }

    public static void makeMockData(Object o) throws Exception {
        String prompt = """
                根据json，生成对象中文模拟测试数据。日期使用yyyy-MM-dd HH:mm:ss 。 各种编号，使用Long
                """;
        prompt += JSON.toJSONString(o,WriteMapNullValue);
        String rs = mistral(prompt);
        //匹配``` ``` 中间的内容
        String json = ReUtil.get("```json(.*?)```", rs, 1).trim();
        Object n = JSON.parseObject(json, o.getClass(),NullOnError);
        BeanUtil.copyProperties(n, o);
    }/*
    public static void main(String[] args) {
        try {
            String prompt = """
                    根据json，生成对象中文模拟测试数据。
                    """;
            prompt += JSON.toJSONString(new Expert(),WriteMapNullValue);
            long start = System.currentTimeMillis();
            String rs = callWithMessage(prompt);
            //匹配``` ``` 中间的内容
            String json = ReUtil.get("```json(.*?)```", rs, 1).trim();
            System.out.println(System.currentTimeMillis() - start);
            System.out.println(prompt);
            System.out.println(rs);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
*/
}